// pages/announcement/announcement.ts
import { MerchantAPI } from '../../utils/api'

/**
 * 公告数据接口（对应后端 AnnouncementListVO）
 */
interface Announcement {
  announcementId: number;
  title: string;
  displayTitle?: string;      // 显示标题（超过20字会截断）
  content?: string;           // 列表中是 contentSummary
  contentSummary?: string;    // 内容摘要
  status: number;             // 0-草稿，1-已发布，2-已下线
  statusName: string;         // 状态名称
  publishTime?: string;       // 发布时间
  createdAt: string;          // 创建时间
  updatedAt?: string;         // 更新时间
}

interface AnnouncementPageData {
  loading: boolean;
  refreshing: boolean;
  announcements: Announcement[];
  
  // 创建/编辑公告
  showCreateModal: boolean;
  editingAnnouncement: Announcement | null;
  announcementForm: {
    title: string;
    content: string;
    status: number;           // 0-草稿，1-发布
    publishTime: string;      // 发布时间
  };
  
  // 分页
  pageNum: number;
  pageSize: number;
  total: number;
  hasMore: boolean;
  
  // 筛选条件
  filterStatus: number | null;  // null表示全部，0-草稿，1-已发布，2-已下线
}

Page({
  data: {
    loading: false,
    refreshing: false,
    announcements: [],
    
    // 创建/编辑公告
    showCreateModal: false,
    editingAnnouncement: null,
    announcementForm: {
      title: '',
      content: '',
      status: 1,              // 默认立即发布
      publishTime: ''
    },
    
    // 分页
    pageNum: 1,
    pageSize: 10,
    total: 0,
    hasMore: true,
    
    // 筛选条件
    filterStatus: null        // null表示全部
  } as AnnouncementPageData,

  onLoad() {
    this.loadAnnouncements(true);
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadAnnouncements(true);
  },

  /**
   * 加载公告列表
   * @param reset 是否重置列表（下拉刷新时为true）
   */
  async loadAnnouncements(reset: boolean = false) {
    if (this.data.loading) return;
    
    // 如果是重置，清空列表并重置页码
    if (reset) {
      this.setData({
        pageNum: 1,
        announcements: [],
        hasMore: true
      });
    }
    
    // 如果没有更多数据，直接返回
    if (!reset && !this.data.hasMore) {
      return;
    }

    this.setData({ loading: true });

    try {
      // 构建查询参数，过滤掉 null/undefined 值
      const params: any = {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      };
      
      // 只有当 filterStatus 不为 null 时才添加 status 参数
      if (this.data.filterStatus !== null) {
        params.status = this.data.filterStatus;
      }
      
      // 调用后端API查询公告列表
      const response = await MerchantAPI.getAnnouncementList(params);

      console.log('公告列表响应:', response);

      if (response && response.code === 200) {
        const newAnnouncements: Announcement[] = response.rows || [];
        const total = response.total || 0;
        
        // 处理公告数据，添加显示标题（超过20字截断）
        const processedAnnouncements = newAnnouncements.map((item: any) => {
          const title = item.title || '';
          return {
            ...item,
            displayTitle: title.length > 20 ? title.substring(0, 20) + '...' : title
          };
        });
        
        // 合并数据（追加模式）
        const announcements = reset ? processedAnnouncements : [...this.data.announcements, ...processedAnnouncements];
        
        this.setData({
          announcements: announcements,
          total: total,
          hasMore: announcements.length < total,
          pageNum: this.data.pageNum + 1
        });
      } else {
        wx.showToast({
          title: response?.msg || '加载失败',
          icon: 'none'
        });
      }

    } catch (error) {
      console.error('加载公告列表失败:', error);
      wx.showToast({
        title: '加载失败，请稍后重试',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false 
      });
    }
  },

  /**
   * 创建公告
   */
  createAnnouncement() {
    // 获取当前时间作为默认发布时间
    const now = new Date();
    const publishTime = this.formatDateTime(now);
    
    // 如果当前筛选的是草稿状态，默认创建草稿；否则默认立即发布
    const defaultStatus = this.data.filterStatus === 0 ? 0 : 1;
    
    this.setData({
      showCreateModal: true,
      editingAnnouncement: null,
      announcementForm: {
        title: '',
        content: '',
        status: defaultStatus,   // 根据筛选状态决定默认状态
        publishTime: publishTime
      }
    });
  },

  /**
   * 编辑公告（只能编辑草稿）
   */
  async editAnnouncement(e: any) {
    const announcement = e.currentTarget.dataset.announcement;
    
    // 只有草稿状态才能编辑
    if (announcement.status !== 0) {
      wx.showToast({
        title: '只能编辑草稿状态的公告',
        icon: 'none'
      });
      return;
    }
    
    // 如果列表中没有完整内容，先获取详情
    let fullContent = announcement.content || announcement.contentSummary || '';
    
    if (!announcement.content && announcement.announcementId) {
      try {
        wx.showLoading({ title: '加载中...' });
        const response = await MerchantAPI.getAnnouncementDetail(announcement.announcementId);
        wx.hideLoading();
        
        if (response && response.code === 200 && response.data) {
          fullContent = response.data.content || '';
        }
      } catch (error) {
        wx.hideLoading();
        console.error('获取公告详情失败:', error);
      }
    }
    
    this.setData({
      showCreateModal: true,
      editingAnnouncement: announcement,
      announcementForm: {
        title: announcement.title,
        content: fullContent,
        status: announcement.status,
        publishTime: announcement.publishTime || this.formatDateTime(new Date())
      }
    });
  },

  /**
   * 保存公告
   */
  async saveAnnouncement() {
    const { announcementForm, editingAnnouncement } = this.data;
    
    console.log('开始保存公告，表单数据:', announcementForm);
    
    // 表单验证
    const title = announcementForm.title ? announcementForm.title.trim() : '';
    const content = announcementForm.content ? announcementForm.content.trim() : '';
    
    if (!title) {
      wx.showToast({
        title: '请输入公告标题',
        icon: 'none'
      });
      return;
    }
    
    if (!content) {
      wx.showToast({
        title: '请输入公告内容',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '保存中...' });

    try {
      let response;
      
      if (editingAnnouncement) {
        // 更新公告（只能更新草稿）
        const updateParams: any = {
          title: title,
          content: content
        };
        
        // 如果是发布状态，添加发布时间
        if (announcementForm.status === 1 && announcementForm.publishTime) {
          updateParams.publishTime = announcementForm.publishTime;
        }
        
        console.log('更新公告参数:', updateParams);
        response = await MerchantAPI.updateAnnouncement(
          editingAnnouncement.announcementId,
          updateParams
        );
      } else {
        // 创建公告
        const createParams: any = {
          title: title,
          content: content,
          status: announcementForm.status
        };
        
        // 如果是发布状态，添加发布时间
        if (announcementForm.status === 1 && announcementForm.publishTime) {
          createParams.publishTime = announcementForm.publishTime;
        }
        
        console.log('创建公告参数:', createParams);
        response = await MerchantAPI.createAnnouncement(createParams);
      }

      wx.hideLoading();
      
      console.log('保存公告响应:', response);

      if (response && response.code === 200) {
        wx.showToast({
          title: editingAnnouncement ? '更新成功' : (announcementForm.status === 1 ? '发布成功' : '保存成功'),
          icon: 'success'
        });

        this.setData({
          showCreateModal: false
        });

        // 重新加载公告列表
        this.loadAnnouncements(true);
      } else {
        wx.showToast({
          title: response?.msg || '操作失败',
          icon: 'none',
          duration: 3000
        });
      }

    } catch (error) {
      wx.hideLoading();
      console.error('保存公告失败:', error);
      wx.showToast({
        title: editingAnnouncement ? '更新失败' : '发布失败',
        icon: 'none',
        duration: 3000
      });
    }
  },

  /**
   * 切换公告状态（发布/下线）
   */
  async toggleAnnouncementStatus(e: any) {
    const announcement = e.currentTarget.dataset.announcement;
    
    // 草稿状态需要点击"发布"，已发布状态需要点击"下线"
    let actionText = '';
    let confirmContent = '';
    
    if (announcement.status === 0) {
      // 草稿 -> 发布
      actionText = '发布';
      confirmContent = '确定要发布这个公告吗？';
    } else if (announcement.status === 1) {
      // 已发布 -> 下线
      actionText = '下线';
      confirmContent = '确定要下线这个公告吗？下线后用户将无法看到此公告。';
    }

    wx.showModal({
      title: `${actionText}公告`,
      content: confirmContent,
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: `${actionText}中...` });
          
          try {
            let response;
            
            if (announcement.status === 0) {
              // 草稿 -> 发布
              response = await MerchantAPI.publishAnnouncement(announcement.announcementId);
            } else if (announcement.status === 1) {
              // 已发布 -> 下线
              response = await MerchantAPI.offlineAnnouncement(announcement.announcementId);
            }

            wx.hideLoading();

            if (response && response.code === 200) {
              wx.showToast({
                title: `${actionText}成功`,
                icon: 'success'
              });

              // 重新加载公告列表
              this.loadAnnouncements(true);
            } else {
              wx.showToast({
                title: response?.msg || `${actionText}失败`,
                icon: 'none'
              });
            }

          } catch (error) {
            wx.hideLoading();
            console.error(`${actionText}公告失败:`, error);
            wx.showToast({
              title: `${actionText}失败`,
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 删除公告
   */
  deleteAnnouncement(e: any) {
    const announcement = e.currentTarget.dataset.announcement;
    
    wx.showModal({
      title: '删除公告',
      content: '确定要删除这个公告吗？删除后无法恢复。',
      confirmColor: '#d9534f',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          
          try {
            const response = await MerchantAPI.deleteAnnouncement(announcement.announcementId);
            wx.hideLoading();

            if (response && response.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });

              // 重新加载公告列表
              this.loadAnnouncements(true);
            } else {
              wx.showToast({
                title: response?.msg || '删除失败',
                icon: 'none'
              });
            }

          } catch (error) {
            wx.hideLoading();
            console.error('删除公告失败:', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 查看公告详情
   */
  async viewAnnouncementDetail(e: any) {
    const announcement = e.currentTarget.dataset.announcement;
    
    try {
      wx.showLoading({ title: '加载中...' });
      const response = await MerchantAPI.getAnnouncementDetail(announcement.announcementId);
      wx.hideLoading();
      
      if (response && response.code === 200 && response.data) {
        const detail = response.data;
        
        // 显示公告详情
        wx.showModal({
          title: detail.title,
          content: `${detail.content}\n\n发布时间：${detail.publishTime || '未发布'}\n创建时间：${detail.createdAt}`,
          showCancel: false,
          confirmText: '关闭'
        });
      } else {
        wx.showToast({
          title: response?.msg || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('获取公告详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.setData({ refreshing: true });
    this.loadAnnouncements(true);
  },
  
  /**
   * 上拉加载更多
   */
  onLoadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadAnnouncements(false);
    }
  },

  // 表单输入处理
  onTitleInput(e: any) {
    this.setData({
      'announcementForm.title': e.detail.value
    });
  },

  onContentInput(e: any) {
    this.setData({
      'announcementForm.content': e.detail.value
    });
  },

  onStatusChange(e: any) {
    const status = parseInt(e.detail.value);
    const publishTime = status === 1 ? this.formatDateTime(new Date()) : '';
    
    this.setData({
      'announcementForm.status': status,
      'announcementForm.publishTime': publishTime
    });
  },

  onPublishTimeChange(e: any) {
    // 如果需要自定义发布时间，可以在这里处理
    this.setData({
      'announcementForm.publishTime': e.detail.value
    });
  },

  // 弹窗控制
  closeCreateModal() {
    this.setData({
      showCreateModal: false,
      editingAnnouncement: null
    });
  },

  preventClose() {
    // 阻止事件冒泡
  },
  
  /**
   * 格式化日期时间
   * @param date Date对象
   * @returns 格式化后的字符串 yyyy-MM-dd HH:mm:ss
   */
  formatDateTime(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  
  /**
   * 切换筛选状态
   */
  onFilterStatusChange(e: any) {
    const index = parseInt(e.detail.value);
    // 索引0表示全部，索引1-3分别对应状态0-2
    const status = index === 0 ? null : index - 1;
    
    this.setData({
      filterStatus: status
    });
    
    // 重新加载数据
    this.loadAnnouncements(true);
  }
});









